import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/routes/app_routes.dart';

import '../../../services/api_service.dart';
import '../../../services/common_service.dart';

class ForgetPasswordLogic extends GetxController {
  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();

  var isSending = false.obs;
  var countdown = 60.obs;

  final formKey = GlobalKey<FormState>();
  final mobileController = TextEditingController();
  final codeController = TextEditingController();

  Timer? _timer;

  @override
  void onInit() {
    super.onInit();
    mobileController.text = commonService.getUser().mobile ?? '';
  }

  void getSmsCode() async {
    if (!formKey.currentState!.validate()) {
      return;
    }

    EasyLoading.show(status: '正在发送验证码...');
    _startCountdown();

    var result = await apiService.sendSmsCode(mobileController.text);
    EasyLoading.dismiss();
    if (result == null) {
      EasyLoading.showError('网络错误，请稍后重试！');
      return;
    } else {
      Get.snackbar('提示', '短信已经下发，${result.ttlDesc}内有效');
    }
  }

  void submit() async {
    if (!formKey.currentState!.validate()) {
      return;
    }

    if(codeController.text.isEmpty) {
      Get.snackbar('提示', '请输入验证码');
      return;
    }

    EasyLoading.show(status: '正在提交...');
    var result = await apiService.verifySmsCode(
      mobileController.text,
      codeController.text,
    );
    EasyLoading.dismiss();
    if (result == null) {
      EasyLoading.showError('网络错误，请稍后重试！');
      return;
    }
    if (result.value['success'] == false) {
      EasyLoading.showError(result.value['error']['message']);
      return;
    }

    Get.toNamed(RouteGet.resetPassword,
        arguments: result.value['data']['token']);
  }

  void _startCountdown() {
    countdown.value = 60;
    isSending.value = true;

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      countdown.value--;
      if (countdown.value <= 0) {
        isSending.value = false;
        _timer?.cancel();
      }
    });
  }

  @override
  void onClose() {
    _timer?.cancel();
    super.onClose();
  }
}
